<?php
class AppController extends Controller {

	var $helpers = array('Html', 'Form', 'Javascript');
    var $authUser = array();

	function beforeFilter(){
		//Get Authorized User
		$this->authUser = $this->Session->read("authorizedUser");
		if(empty($this->authUser) && $this->params['controller']!='login'){
			$this->redirect('/login');
		}
		//pr($authUser);
		//Check is user authorized to acces current controller
		$this->loadModel('Usergroup');
		$userGroupModel = new Usergroup();
		$authController = $userGroupModel->getAuthorizedController($this->authUser['UserGroup']['id']);
		//pr($authController);
		if((empty($authController) || !in_array($this->params['controller'],$authController)) && $this->params['controller']!='login'){
			$this->redirect('/login/access_denied');
		}
		$this->set('authorizedUser',$this->authUser);
		$this->loadModel('Module');
		$this->loadModel('Menu');

        $this->_prepareLogInfo();

		//Getting Current Menu
		$url = "/".$this->params['controller'];
		$m1 = new Menu();
		$currentMenu = $m1->find('first',array('conditions'=>array('link'=>$url)));
		$this->set('currentMenu',$currentMenu);

		//List Available Menu
		$m = new Module();
		$m->Menu->order = 'Menu.label ASC';
		$this->set("m",$userGroupModel->getAuthorizedModule($this->authUser['UserGroup']['id']));
	}

    private function _prepareLogInfo()
    {
        $this->loadModel('Worklog');

        // get today data
        $today = $this->Worklog->find(array("date(Worklog.start)"=>date("Y-m-d"),"User.id" => $this->authUser['User']['id']));
        $startTime = '--:--';
        $activeTime = '00:00';
        if(isset($today['Worklog']['start'])){
            $startTime = substr($today['Worklog']['start'], 11, 5);
        }
        if(isset($today['Worklog']['active_time'])){
            $activeTime = substr($today['Worklog']['active_time'], 0, 5);
        }
        $this->set(compact('startTime', 'activeTime'));

        // get accumulative late hour for this month
        $this->set('lateTime', $this->Worklog->getLateByUser($this->authUser['User']['id']));

        $interval['log'] = 10 * 60 ;   // 10 minutes
        $interval['updateActivity'] = 1 * 60 ;  // 1 minutes
        $this->set('interval', $interval);
    }
}
?>
